<template>
  <div class="article-list-container">
    <div class="article-list-header">
      <div class="header-left">
        <h2>文章管理</h2>
        <p class="header-subtitle">共 {{ pagination.total }} 篇文章</p>
      </div>
      <a-button type="primary" @click="handleAddArticle" class="add-article-button">
        <template #icon><PlusOutlined /></template>
        新增文章
      </a-button>
    </div>
    
    <a-card class="article-card">
      <div class="article-list-toolbar">
        <div class="toolbar-row">
          <a-input
            v-model:value="searchKeyword"
            placeholder="搜索文章标题"
            style="width: 300px; margin-right: 16px;"
            allowClear
            @change="handleSearch"
            class="search-input"
          />
          
          <a-select
            v-model:value="selectedCategory"
            placeholder="选择分类"
            style="width: 150px; margin-right: 16px;"
            @change="handleSearch"
            class="filter-select"
          >
            <a-select-option v-for="category in categories" :key="category._id || category.id" :value="category._id || category.id">
              {{ category.name }}
            </a-select-option>
          </a-select>
          
          <a-select
            v-model:value="selectedStatus"
            placeholder="文章状态"
            style="width: 120px; margin-right: 16px;"
            @change="handleSearch"
            class="filter-select"
          >
            <a-select-option value="published">已发布</a-select-option>
            <a-select-option value="draft">草稿</a-select-option>
             <a-select-option value="">全部</a-select-option>
          </a-select>
        </div>
        
        <div class="toolbar-row" style="margin-top: 12px;">
          <a-date-picker
            v-model:value="dateRange"
            style="width: 280px;"
            placeholder="选择发布时间范围"
            @change="handleSearch"
            :picker="'range'"
            class="date-range-picker"
          />
          
          <a-button type="default" @click="resetFilters" class="reset-button">
            重置筛选
          </a-button>
        </div>
      </div>
      
      <div class="table-container">
        <a-table
          :columns="columns"
          :data-source="articles"
          :pagination="pagination"
          row-key="_id"
          :loading="loading"
          class="article-table"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'title'">
              <a :href="'#/articles/' + record._id" target="_blank" class="article-title-link">
                {{ record.title }}
              </a>
            </template>
            <template v-else-if="column.key === 'category'">
              <a-tag color="blue" class="category-tag">
                {{ record.category.name }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'tags'">
              <div v-if="record.tagIds || record.tags" class="tag-container">
                <a-tag
                  v-for="(tag, index) in record.tags"
                  :key="index"
                  color="purple"
                  class="article-tag"
                >
                  {{ tag.name }}
                </a-tag>
              </div>
              <span v-else>-</span>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="record.status === 'published' ? 'success' : 'default'" class="status-tag">
                {{ record.status === 'published' ? '已发布' : '草稿' }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'publishDate'">
              <span>{{ record.publishDate || record.createdAt || '-' }}</span>
            </template>
            <template v-else-if="column.key === 'views'">
              <span>{{ record.views || 0 }}</span>
            </template>
            <template v-else-if="column.key === 'action'">
              <a-space size="middle" class="action-buttons">
              <a-button size="small" @click="handleEdit(record)" class="edit-button">
                <template #icon><EditOutlined /></template>
              </a-button>
              <a-button size="small" type="primary" @click="handlePublish(record)" v-if="record.status === 'draft'" class="publish-button">
                <template #icon><CheckOutlined /></template>
              </a-button>
              <a-popconfirm
                title="确定要删除这篇文章吗？"
                description="删除后将无法恢复，是否继续？"
                @confirm="handleDelete(record._id)"
                ok-text="确定"
                cancel-text="取消"
              >
                <a-button size="small" danger class="delete-button">
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </a-popconfirm>
            </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { message, Popconfirm } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import articleApi from '@/api/article'
import categoryApi from '@/api/category'
import tagApi from '@/api/tag'

const router = useRouter()
const loading = ref(false)
const searchKeyword = ref('')
const selectedCategory = ref('')
const selectedStatus = ref('')
const dateRange = ref(null)
const articles = ref([])
const categories = ref([])
const tags = ref([])

const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => {
    return `第 ${range[0]}-${range[1]} 条，共 ${total} 条`
  },
  onChange: (page, pageSize) => {
    pagination.current = page
    pagination.pageSize = pageSize
    fetchArticles()
  },
  onShowSizeChange: (page, pageSize) => {
    pagination.current = page
    pagination.pageSize = pageSize
    fetchArticles()
  },
  size: 'middle'
})

const columns = [
  {
    title: '标题',
    dataIndex: 'title',
    key: 'title',
    ellipsis: true,
    width: 400,
    sorter: (a, b) => a.title.localeCompare(b.title)
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    width: 150
  },
  {
    title: '标签',
    dataIndex: 'tags',
    key: 'tags',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
    width: 100,
    filters: [
      { text: '已发布', value: 'published' },
      { text: '草稿', value: 'draft' }
    ],
    onFilter: (value, record) => record.status === value
  },
  {
    title: '发布时间',
    dataIndex: 'publishDate',
    key: 'publishDate',
    width: 180,
    sorter: (a, b) => new Date(a.publishDate || 0) - new Date(b.publishDate || 0)
  },
  {
    title: '浏览量',
    dataIndex: 'views',
    key: 'views',
    width: 100,
    sorter: (a, b) => a.views - b.views
  },
  {
    title: '操作',
    key: 'action',
    width: 200,
    fixed: 'right'
  }
]

const fetchArticles = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current,
      pageSize: pagination.pageSize,
      keyword: searchKeyword.value,
      categoryId: selectedCategory.value,
      status: selectedStatus.value,
      startDate: dateRange.value ? dateRange.value[0].format('YYYY-MM-DD') : '',
      endDate: dateRange.value ? dateRange.value[1].format('YYYY-MM-DD') : ''
    }
    
    const response = await articleApi.getArticles(params)
    if (response.code === 200 && response.data) {
      articles.value = response.data.list || []
      pagination.total = response.data.total || 0
    }
  } catch (error) {
    message.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

const fetchCategories = async () => {
  try {
    const response = await categoryApi.getCategories()
    if (response.code === 200 && response.data) {
      // Handle both direct data and nested data structure
      const data = response.data.data || response.data
      categories.value = [
        { id: '', name: '全部分类' },
        ...(Array.isArray(data) ? data : [])
      ]
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  }
}

const fetchTags = async () => {
  try {
    const response = await tagApi.getTags()
    if (response.code === 200 && response.data) {
      tags.value = response.data
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
  }
}



const handleSearch = () => {
  pagination.current = 1
  fetchArticles()
}

const resetFilters = () => {
  searchKeyword.value = ''
  selectedCategory.value = ''
  selectedStatus.value = ''
  dateRange.value = null
  pagination.current = 1
  fetchArticles()
}

const handleAddArticle = () => {
  router.push('/articles/create')
}

const handleEdit = (record) => {
  router.push(`/articles/edit/${record._id}`)
}

const handlePublish = async (record) => {
  try {
    const response = await articleApi.updateArticleStatus(record._id, 'published')
    if (response.code === 200) {
      message.success('发布成功')
      fetchArticles()
    } else {
      message.error(response.message || '发布失败')
    }
  } catch (error) {
    message.error('发布失败')
  }
}

const handleDelete = async (id) => {
  try {
    const response = await articleApi.deleteArticle(id)
    if (response.code === 200) {
      message.success('删除成功')
      fetchArticles()
    } else {
      message.error(response.message || '删除失败')
    }
  } catch (error) {
    message.error('删除失败')
  }
}

onMounted(() => {
  fetchCategories()
  fetchTags()
  fetchArticles()
})
</script>

<style scoped>
.article-list-container {
  width: 100%;
  height: 100%;
  padding: 24px;
}

.article-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding: 0 4px;
}

.header-left h2 {
  margin-bottom: 4px;
  color: #262626;
  font-size: 20px;
}

.header-subtitle {
  font-size: 14px;
  color: #999;
  margin: 0;
}

.add-article-button {
  height: 40px;
  font-size: 14px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.add-article-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
}

.article-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
  transition: all 0.3s ease;
}

.article-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.article-list-toolbar {
  padding: 16px;
  background-color: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.toolbar-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.search-input {
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.search-input:focus {
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.filter-select {
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.date-range-picker {
  border-radius: 6px;
  font-size: 14px;
}

.reset-button {
  height: 32px;
  border-radius: 6px;
  font-size: 14px;
  transition: all 0.3s ease;
}

.reset-button:hover {
  background-color: #f5f5f5;
}

.table-container {
  padding: 0;
}

.article-table {
  border-radius: 8px;
  overflow: hidden;
}

.article-table .ant-table-thead > tr > th {
  background-color: #fafafa;
  font-weight: 500;
  color: #262626;
  border-bottom: 1px solid #f0f0f0;
}

.article-table .ant-table-tbody > tr {
  transition: all 0.3s ease;
}

.article-table .ant-table-tbody > tr:hover > td {
  background-color: #f5f5f5;
}

.article-title-link {
  color: #262626;
  text-decoration: none;
  transition: all 0.3s ease;
  font-weight: 500;
}

.article-title-link:hover {
  color: #1890ff;
  text-decoration: underline;
}

.category-tag,
.status-tag {
  border-radius: 4px;
  font-size: 12px;
  height: 22px;
  padding: 0 8px;
}

.tag-container {
  display: flex;
  flex-wrap: wrap;
  gap: 4px;
}

.article-tag {
  border-radius: 4px;
  font-size: 12px;
  height: 22px;
  padding: 0 8px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-button,
.publish-button,
.delete-button {
  height: 28px;
  font-size: 12px;
  padding: 0 12px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.edit-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.publish-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(24, 144, 255, 0.3);
}

.delete-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(255, 77, 79, 0.3);
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .toolbar-row {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input,
  .filter-select,
  .date-range-picker {
    width: 100% !important;
    margin-right: 0 !important;
  }
}

@media (max-width: 768px) {
  .article-list-container {
    padding: 16px;
  }
  
  .article-list-header {
    flex-direction: column;
    align-items: stretch;
    gap: 16px;
  }
  
  .add-article-button {
    width: 100%;
  }
  
  .article-table {
    font-size: 12px;
  }
}
</style>